#include "order.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h> // Needed for snprintf

// 加载所有订单信息到链表，返回订单数量
// filename is expected to be the base filename (e.g., "orders.dat")
int load_orders(const char* filename, OrderNode** head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "rb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        *head = NULL;
        return 0;
    }
    Order temp;
    int count = 0;
    *head = NULL;
    OrderNode* tail = NULL;
    while (fread(&temp, sizeof(Order), 1, fp) == 1) {
        OrderNode* node = (OrderNode*)malloc(sizeof(OrderNode));
        if (!node) break;
        node->data = temp;
        node->next = NULL;
        if (*head == NULL) {
            *head = node;
        } else {
            tail->next = node;
        }
        tail = node;
        count++;
    }
    fclose(fp);
    return count;
}

// 保存所有订单信息到文件，返回保存的订单数量
// filename is expected to be the base filename (e.g., "orders.dat")
int save_orders(const char* filename, OrderNode* head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "wb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        return 0;
    }
    int count = 0;
    OrderNode* p = head;
    while (p) {
        if (fwrite(&p->data, sizeof(Order), 1, fp) != 1) break;
        p = p->next;
        count++;
    }
    fclose(fp);
    return count;
}

// 添加新订单到链表尾部，若编号已存在则不添加，返回1成功，0已存在
int add_order(OrderNode** head, const Order* new_order) {
    if (find_order_by_id(*head, new_order->id)) {
        // 已存在该编号订单，不添加
        return 0;
    }
    OrderNode* node = (OrderNode*)malloc(sizeof(OrderNode));
    if (!node) return 0;
    node->data = *new_order;
    node->next = NULL;
    if (*head == NULL) {
        *head = node;
    } else {
        OrderNode* p = *head;
        while (p->next) p = p->next;
        p->next = node;
    }
    return 1;
}

// 根据订单编号删除订单，成功返回1，失败返回0
int delete_order(OrderNode** head, int order_id) {
    OrderNode* p = *head, *prev = NULL;
    while (p) {
        if (p->data.id == order_id) {
            if (prev) prev->next = p->next;
            else *head = p->next;
            free(p);
            return 1;
        }
        prev = p;
        p = p->next;
    }
    return 0;
}

// 查找订单，返回指向该节点的指针，未找到返回NULL
OrderNode* find_order_by_id(OrderNode* head, int order_id) {
    while (head) {
        if (head->data.id == order_id) return head;
        head = head->next;
    }
    return NULL;
}

// 修改订单信息，成功返回1，失败返回0
int update_order(OrderNode* head, const Order* updated_order) {
    OrderNode* node = find_order_by_id(head, updated_order->id);
    if (!node) return 0;
    node->data = *updated_order;
    return 1;
}

// 按用户、饮品、时间等条件查询订单，返回链表（需手动释放）
OrderNode* query_orders(OrderNode* head, int user_id, int drink_id, time_t start_time, time_t end_time, int status) {
    OrderNode* result = NULL, *tail = NULL;
    while (head) {
        int match = 1;
        if (user_id > 0 && head->data.user_id != user_id) match = 0;
        if (drink_id > 0 && head->data.drink_id != drink_id) match = 0;
        if (start_time > 0 && head->data.order_time < start_time) match = 0;
        if (end_time > 0 && head->data.order_time > end_time) match = 0;
        if (status >= 0 && head->data.status != status) match = 0;
        if (match) {
            OrderNode* node = (OrderNode*)malloc(sizeof(OrderNode));
            if (!node) break;
            node->data = head->data;
            node->next = NULL;
            if (!result) result = node;
            else tail->next = node;
            tail = node;
        }
        head = head->next;
    }
    return result;
}

// 打印所有订单信息（调试用）
void print_all_orders(OrderNode* head) {
    printf("订单号\t用户ID\t饮品ID\t数量\t下单时间\t\t状态\n");
    while (head) {
        char timebuf[32];
        struct tm* tminfo = localtime(&head->data.order_time);
        strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M", tminfo);
        const char* status_str = "待处理";
        if (head->data.status == ORDER_STATUS_FINISHED) status_str = "已完成";
        else if (head->data.status == ORDER_STATUS_CANCELED) status_str = "已取消";
        printf("%d\t%d\t%d\t%d\t%s\t%s\n",
            head->data.id,
            head->data.user_id,
            head->data.drink_id,
            head->data.quantity,
            timebuf,
            status_str
        );
        head = head->next;
    }
}

// 释放链表内存
void free_all_orders(OrderNode* head) {
    while (head) {
        OrderNode* tmp = head;
        head = head->next;
        free(tmp);
    }
}